﻿import component, { ComType } from "../core/tool/component";
import { BattleArea } from "../core/rpg/battleArea";
import common from "../core/tool/common";
import type { ActiveBuff, Skill, Buff } from "../core/rpg/types";
import { SkillType, LogType, TargetType, PassiveTriggerType, attackKey, Attribute_base } from "../shared/face/enums";
import base_component from "./base_component";
import { Icard } from "../core/tool/Icard";
import equip_component from "./equip_component";
import { analysisIntent } from "../core/tool/baseScene";
import SkillManager from "../core/rpg/skill/SkManager";
import gameCfg from "../gameCfg";
import follow_component from "./follow_component";
import talent_component from "./talent_component";
import BattleLogger from "../core/rpg/BattleLogger";
import { RPGClientHandler } from "../core/rpg/RPGClientHandler";
import { RPGService } from "../service/RPGService";
import { DataSkill } from "../shared/face";

/**
 * RPG组件 - 现代化组件，使用依赖注入
 * 职责：
 * 1. 管理角色等级、经验、生命值等状态
 * 2. 处理技能学习和使用
 * 3. 管理战斗状态和属性
 * 4. 显示RPG相关界面
 * 5. 通过注入的RPGService处理业务逻辑
 */
export default class rpg_component extends component {
    private _rpgService: RPGService;
    level: number = 1;
    
    exp: { now: number, max: number } = { now: 0, max: 10 };
    hp_now: number = 100;
    lastAttTickTime: number = 0;
    shield_now: number = 0; // 当前护盾值
    selfSkill: DataSkill[] = [];
    /**
     * 战力
     */
    _fighting: number = 0;
    masterId: string = '';
    //, data: { [key: string]: any }
    // 永久基础属性
    attribute: { key: Attribute_base, val: number }[] = [];
    get outSkills(): { skillId: string; reName?: string; cooldown: number; desc?: string }[] {
        if (this._tempSkills.length == 0) {
            this.reload_skills();
        }
        return this._tempSkills;
    }

    _equipSkills: { skillId: string; reName?: string; cooldown: number; desc?: string }[] = [];
    _tempSkills: { skillId: string; reName?: string; cooldown: number; desc?: string }[] = [];
    _isHome: boolean = false;
    _activeBuffs: ActiveBuff[] = [];
    _currentTarget: rpg_component | null = null; // 当前目标
    _lastUsedSkill: string = '';
    _usedSkills: string[] = []; // 已使用的技能
    _tempBoosts: Map<string, Map<string, number>> = new Map(); // 记录每个 Buff 的临时提升值
    _battleArea!: BattleArea;
    /**
     * 客户端处理器
     */
    _clientHandler: RPGClientHandler;

    constructor() {
        super();
        // 使用依赖注入获取RPGService（_开头，不会被持久化）
        this._rpgService = this.getService<RPGService>('RPGService');
        // 初始化客户端处理器
        this._clientHandler = new RPGClientHandler(this);
    }

    /**
     * 根据ID查找对应的rpg_component实例
     */
    private findRpgComponentById(id: string): rpg_component {
        // 这里需要根据实际的游戏架构来实现
        // 暂时返回自身，实际应该从战场或游戏管理器中查找
        return this;
    }
    reload_skills(): { skillId: string; reName?: string; cooldown: number; desc?: string }[] {
        let skills: { skillId: string; reName?: string; cooldown: number; desc?: string }[] = [];
        this._equipSkills = [];

        // 添加装备技能
        let equip_com = this.getComponent(ComType.装备栏) as equip_component;
        equip_com.slot.forEach(equip => {
            if (!equip.skill.length) {
                return;
            }
            equip.skill.forEach(skill => {
                if (!skill.skillId) {
                    return;
                }
                this._equipSkills.push({...skill,cooldown:skill.cooldown || 0});
                skills.push({...skill,cooldown:skill.cooldown || 0});
            });
        });

        // 添加自身技能
        this.selfSkill.forEach(skill => {
            if (!skill.skillId) {
                console.warn('发现无效技能:', skill);
                return;
            }
            skills.push({ skillId: skill.skillId, reName: skill.reName, cooldown: skill.cooldown || 0, desc: skill.desc });
        });

        this._tempSkills = skills;
        BattleLogger.log('info', '重新加载技能完成', {
            skillList: skills.map(s => s.skillId),
            unitId: this.id
        });
        return skills;
    }
    /**
     * 初始化组件
     */
    init() {
        this.setUp_default();
    }

    /**
     * 测试方法
     * @param cfg 配置数据
     */
    test(cfg: any) {
        this.level = cfg.level;
        this.selfSkill = cfg.skill;
    }
    /**
     * 战力计算
     */
    fighting_update() {
        this._fighting = 0;
        let 物理攻击 = this.getAttribute(Attribute_base.物理攻击);
        let 魔法攻击 = this.getAttribute(Attribute_base.魔法攻击);
        let 物理防御 = this.getAttribute(Attribute_base.物理防御);
        let 魔法防御 = this.getAttribute(Attribute_base.魔法防御);
        let 最大生命值 = this.getAttribute(Attribute_base.最大生命值);
        let 物理暴击率 = this.getAttribute(Attribute_base.物理暴击率);
        let 魔法暴击率 = this.getAttribute(Attribute_base.魔法暴击率);
        let 物理穿透 = this.getAttribute(Attribute_base.物理穿透);
        let 魔法穿透 = this.getAttribute(Attribute_base.魔法穿透);
        let 技能缩减 = this.getAttribute(Attribute_base.技能缩减);
        let 生命恢复 = this.getAttribute(Attribute_base.生命恢复);
        // 改进的战力计算公式
        this._fighting += 物理攻击 * 10;
        this._fighting += 魔法攻击 * 10;
        this._fighting += ((物理防御 + 最大生命值) * 0.1) * 5 + ((魔法防御 + 最大生命值) * 0.1) * 5;
        this._fighting += (物理暴击率 * 物理攻击) * 0.2;
        this._fighting += (魔法暴击率 * 魔法攻击) * 0.2;
        this._fighting += (物理穿透 * 物理攻击);
        this._fighting += (魔法穿透 * 魔法攻击);
        this._fighting += (技能缩减 * this.level);
        this._fighting += 生命恢复;
        let _pets = this.getComponent(ComType.随从) as follow_component;
        if (_pets._pets.length > 0) {
            for (let pet of _pets._pets) {
                pet.getComponent(ComType.rpg).fighting_update();
                this._fighting += pet.getComponent(ComType.rpg)._fighting;
            }
        }
        // 取整
        this._fighting = Math.round(this._fighting);
    }
    battle_read(bt: BattleArea, isHome: boolean) {
        this.reload_skills();
        this._battleArea = bt;
        this._isHome = isHome;
    }
    config_setUp(config: any) {
        this.level = config.level;
        this.selfSkill = config.skill;
        for (let i = 0; i < config.attribute.length; i++) {
            this.attribute.push({ key: config.attribute[i].attribute, val: config.attribute[i].value });
        }
        this.hp_now = this.getAttribute(Attribute_base.最大生命值);
        this.addSk({ skillId: 'A000' });
    }
    /**
     * 给自身永久添加技能
     * @param skill 
     */
    /**
     * 添加技能
     * @param skill 技能数据
     */
    addSk(skill: { skillId: string; reName?: string; cooldown?: number; desc?: string }) {
        // 转换技能数据以匹配addSkillToList的期望类型
        const skillsForAdd = this.selfSkill.map(s => ({
            skillId: s.skillId,
            reName: s.reName,
            cooldown: s.cooldown || 0,
            desc: s.desc
        }));
        const skillForAdd = { skillId: skill.skillId, reName: skill.reName, cooldown: skill.cooldown || 0, desc: skill.desc };
        const result = this._rpgService.addSkillToList(skillsForAdd, skillForAdd, this.id);

        if (result.success) {
            // 将基础技能数据转换回扩展技能数据
            const newSkill = {
                skillId: skill.skillId,
                reName: skill.reName,
                cooldown: skill.cooldown || 0,
                desc: skill.desc,
                level: 1,
                exp: 0,
                maxLevel: 10,
                permanentBoosts: {},
                useCount: 0
            };
            this.selfSkill = [...this.selfSkill, newSkill];
            this.reload_skills();

            BattleLogger.log('info', '重新加载后技能列表', {
                skillList: this.outSkills.map(s => s.skillId),
                unitId: this.id
            });

            this._clientHandler.showSkillLearned();
        } else {
            console.error('添加技能失败:', result.message);
        }
    }
    /**
     * 设置默认属性
     */
    private setUp_default() {
        this.addSk({ skillId: 'A000' });

        // 使用服务创建默认属性
        const defaultAttributes = this._rpgService.createDefaultAttributes();
        this.attribute.push(...defaultAttributes);

        this.hp_now = this.getAttribute(Attribute_base.最大生命值);
    }
    client_skill() {
        this._clientHandler.showSkillList();
    }
    client_lookAtt(data: any, title?: string) {
        this._clientHandler.showAttributes(data, title);
    }
    /**
     * 重置战斗状态
     */
    reset() {
        const battleState = this._rpgService.initializeBattleState();
        this._usedSkills = battleState.usedSkills;
        this._lastUsedSkill = battleState.lastUsedSkill;
        this._currentTarget = battleState.currentTarget;
    }
    /**
     * 添加经验值
     * @param amount 经验值
     */
    addExp(amount: number) {
        let com_pet = this.getComponent(ComType.随从) as follow_component;

        // 如果有随从，经验需要平分
        if (com_pet._pets.length > 0) {
            const expPerUnit = this._rpgService.distributeExpToPets(amount, com_pet._pets.length);
            // 随从获得经验
            com_pet.addExp(expPerUnit);
            // 玩家获得平分后的经验
            amount = expPerUnit;
        }

        // 记录升级前的等级
        const oldLevel = this.level;

        // 使用服务计算经验变化
        const expResult = this._rpgService.calculateExpChange(
            this.exp.now,
            this.exp.max,
            this.level,
            amount
        );

        // 更新状态
        this.exp.now = expResult.newExp;
        this.exp.max = expResult.newMaxExp;
        this.level = expResult.newLevel;

        // 只在等级真正发生变化时才发送消息
        if (this.level > oldLevel) {
            // 计算实际升级的等级数
            const levelGained = this.level - oldLevel;
            for (let i = 0; i < levelGained; i++) {
                this._clientHandler.showLevelUp(oldLevel + i + 1);
            }
            this._clientHandler.showPowerChange();
        }

        // 处理降级
        if (expResult.levelDownCount > 0) {
            for (let i = 0; i < expResult.levelDownCount; i++) {
                this._clientHandler.showLevelDown();
            }
            this._clientHandler.showPowerChange();
        }
    }
    /**
     * 获取属性值
     * @param key 属性键
     * @returns 属性值
     */
    getAttribute(key: string): number {
        let equip_com = this.getComponent(ComType.装备栏) as equip_component;
        let talent_com = this.getComponent(ComType.血统) as talent_component;

        const finalValue = this._rpgService.calculateAttribute(
            this.attribute,
            key,
            this.level,
            this._tempBoosts,
            equip_com.getAttribute(key),
            talent_com.getAttribute(key)
        );

        if (key == Attribute_base.最大生命值) {
            this._att_tick(finalValue);
        }

        return finalValue;
    }
    /**
     * 属性 tick 计算（生命值恢复）
     * @param max 最大生命值
     */
    private _att_tick(max: number) {
        if (this.lastAttTickTime == 0) {
            this.lastAttTickTime = Date.now();
            return;
        }

        let time = (Date.now() - this.lastAttTickTime) / 1000;
        if (time > 1) {
            this.lastAttTickTime = Date.now();

            if (this.isDie()) {
                return;
            }

            const regenRate = this.getAttribute(Attribute_base.生命恢复);
            const newHp = this._rpgService.calculateHealthRegeneration(
                this.hp_now,
                max,
                regenRate,
                time,
                this.isDie()
            );

            this.hp_now = newHp;
        }
    }
    /**
     * 设置属性值
     * @param key 属性键
     * @param value 属性值
     */
    setAttribute(key: Attribute_base, value: number) {
        const result = this._rpgService.setAttribute(this.attribute, key, value);
        if (result.success) {
            BattleLogger.log('info', '属性设置成功', {
                key,
                oldValue: result.oldValue,
                newValue: value,
                unitId: this.id
            });
        }
    }
    attack(targets: rpg_component[], allies: rpg_component[]): Skill | undefined {
        // 根据id去重
        const uniqueTargets = new Map<string, rpg_component>();
        targets.forEach(target => {
            if (!uniqueTargets.has(target.id)) {
                uniqueTargets.set(target.id, target);
            }
        });
        targets = Array.from(uniqueTargets.values());

        let battleArea = this._battleArea;

        // 添加调试日志
        BattleLogger.log('info', '开始选择技能', {
            unitId: this.id,
            allSkills: this.outSkills.map(s => s.skillId).filter(Boolean)
        });

        const availableSkills = this.outSkills
            .filter(skill => skill.cooldown <= 0)
            .map(skillData => SkillManager.getSkillById(skillData.skillId))
            .filter(skill => skill && (skill.type === SkillType.主动技能)); // 包含主动技能和光环技能

        // 添加调试日志
        BattleLogger.log('info', '可用技能列表', {
            unitId: this.id,
            availableSkills: availableSkills.map(s => s?.id || 'unknown').filter(Boolean)
        });

        if (availableSkills.length > 0) {
            const randomSkill = availableSkills[Math.floor(Math.random() * availableSkills.length)];
            if (randomSkill) {
                // 添加调试日志
                BattleLogger.log('info', '选择使用技能', {
                    unitId: this.id,
                    selectedSkill: randomSkill.id,
                    skillName: randomSkill.name
                });

                let skillData = this.outSkills.find(skillData => skillData.skillId === randomSkill.id)!;
                this._lastUsedSkill = randomSkill.id;
                let localTargets = new Map<TargetType, rpg_component[]>();
                randomSkill.targetType.forEach((targetType, index) => {
                    const range = randomSkill.range?.[index] || 1; // 默认攻击范围为 1
                    const effectTargets = localTargets.get(targetType) || battleArea.selectTargets(this, targetType, allies, targets);
                    localTargets.set(targetType, effectTargets);
                    const actives = effectTargets.slice(0, range); // 选择多个目标
                    actives.forEach(target => {
                        randomSkill.effect(this, target, randomSkill, 1, index, {});
                    });
                });
                skillData.cooldown = randomSkill.cooldown;
                return randomSkill; // 返回释放的技能id
            } else {
                BattleLogger.log('info', '没有找到技能', { unitId: this.id });
            }
        } else {
            BattleLogger.log('info', '没有可用的技能', { unitId: this.id });
            process.exit(0);
        }
        return undefined;
    }
    setLog(unit: rpg_component, target: rpg_component, atKey: attackKey, val: number, skill: Skill | Buff) {
        if (isNaN(val)) {
            return;
        }
        // 记录伤害统计
        if (val == 0) {
            BattleLogger.log('info', '造成0点伤害', {
                skillName: skill.name,
                damage: val,
                unitId: this.id,
                targetId: target.id
            });
            return;
        }

        BattleLogger.log('info', '造成伤害', {
            skillName: skill.name,
            targetId: target.id,
            damage: val,
            attackType: atKey,
            unitId: this.id
        });

        let logType = SkillManager.coverAttkKey(atKey);
        let self = this._battleArea;
        let skillData = this.outSkills.find(skillData => skillData.skillId === skill.id);
        let skName = skillData?.desc || skillData?.reName || skill.name;

        if (logType === LogType.伤害) {
            this.logPlayerStats(this, val, 0, 0);
            this.logPlayerStats(target, 0, val, 0);

            // 记录详细伤害日志
            BattleLogger.logDamage(unit, target, val, atKey, val, skill.id);

            BattleLogger.log('info', '触发被动技能检查', {
                attackType: atKey,
                targetId: target.id,
                unitId: this.id
            });

            if (atKey == attackKey.普通攻击) {
                BattleLogger.log('info', '触发普通攻击被动技能', {
                    targetId: target.id,
                    unitId: this.id
                });
                self.triggerPassiveSkills(target, self.selectTargets(target, TargetType.我方不含自己), [target, ...self.selectTargets(target, TargetType.敌方)], PassiveTriggerType.受到普通攻击时);
            } else {
                BattleLogger.log('info', '触发伤害被动技能', {
                    targetId: target.id,
                    unitId: this.id
                });
                self.triggerPassiveSkills(target, self.selectTargets(target, TargetType.我方不含自己), [target, ...self.selectTargets(target, TargetType.敌方)], PassiveTriggerType.受到伤害时);
            }
        } else if (logType === LogType.治疗) {
            this.logPlayerStats(this, 0, 0, val);

            // 记录详细治疗日志
            BattleLogger.logHealing(unit, target, val, skill.id);
        }

        // 记录战斗日志
        this.logPlayerAction(unit, skName, val, logType);

        if (target.isDie() && logType != LogType.伤害) {
            debugger;
        }
        if (target.isDie()) {
            self.logKill({ masterId: unit.id, round: self.getRound(), skillName: skName, target: target, unit: unit });

            // 记录击杀日志
            BattleLogger.logKill(unit, target, self.getRound(), skill.id);
        }
    }
    private logPlayerStats(unit: rpg_component, damage: number, damageTaken: number, healing: number) {
        let baseCom = unit.getComponent(ComType.base) as base_component;
        let self = this._battleArea;
        const playerStats = self.getPlayerStats();
        if (!playerStats.has(baseCom.id)) {
            playerStats.set(baseCom.id, { damage: 0, damageTaken: 0, healing: 0 });
        }
        const stats = playerStats.get(baseCom.id)!;
        stats.damage += damage;
        stats.damageTaken += damageTaken;
        stats.healing += healing;
    }
    logPlayerAction(unit: rpg_component, skillName: string, amount: number, type: LogType) {
        let baseCom = unit.getComponent(ComType.base) as base_component;
        let self = this._battleArea;
        const playerLogs = self.getPlayerLogs();
        if (!playerLogs.has(baseCom.nickName)) {
            playerLogs.set(baseCom.nickName, []);
        }
        const logs = playerLogs.get(baseCom.nickName)!;
        const logSymbols = {
            [LogType.伤害]: '🗡️',
            [LogType.治疗]: '❤',
            [LogType.护盾]: '🛡️',
        };
        const logSymbol = logSymbols[type];

        // Use a more precise check for existing logs
        const existingLogIndex = logs.findIndex((log: string) => log.startsWith(`${skillName}${logSymbol}`));

        if (existingLogIndex !== -1) {
            const existingLog = logs[existingLogIndex];
            const logParts = existingLog.split(/(🗡️|❤|🔄)/).filter(Boolean);
            const logMap = new Map<string, number>();
            for (let i = 1; i < logParts.length; i += 2) {
                logMap.set(logParts[i], parseInt(logParts[i + 1], 10));
            }
            logMap.set(logSymbol, (logMap.get(logSymbol) || 0) + amount);
            logs[existingLogIndex] = `${skillName}${Array.from(logMap.entries()).map(([symbol, value]) => `${symbol}${value}`).join('')}`;
        } else {
            logs.push(`${skillName}${logSymbol}${amount}`);
        }
    }
    /**
     * 受到伤害
     * @param amount 输入数值
     * @param penetration 防御穿透
     * @returns 
     */
    hit(amount: number, penetration: number = 0, type: attackKey) {
        if (isNaN(amount)) {
            return 0;
        }
        if (this.isDie()) {
            return 0;
        }
        if (type == attackKey.真实攻击) {
            this.hp_now = Math.max(0, this.hp_now - amount);
            return amount;
        }
        // 非线性防御公式（含抗性穿透）
        let level = this.level;
        const effectiveDefense = (this.getAttribute('防御') + 50) * (1 - Math.min(penetration, 0.7));
        const damageReduction = effectiveDefense / (effectiveDefense + 5 * Math.sqrt(level) + 50);

        // 伤害波动 + 下限保护
        const randomized = amount * (0.95 + Math.random() * 0.1); // ±5%浮动
        let finalDamage = Math.max(1, Math.floor(
            randomized * (1 - damageReduction)
        ));

        // 护盾处理
        let shieldAbsorbed = 0;
        if (this.shield_now > 0) {
            shieldAbsorbed = Math.min(this.shield_now, finalDamage);
            this.shield_now -= shieldAbsorbed;
            finalDamage -= shieldAbsorbed;

            // 记录护盾吸收日志
            if (shieldAbsorbed > 0) {
                BattleLogger.log('info', '护盾吸收伤害', {
                    unitId: this.id,
                    shieldAbsorbed,
                    remainingShield: this.shield_now,
                    remainingDamage: finalDamage
                });
            }
        }

        if (isNaN(this.hp_now)) {
            debugger;
        }
        // 生命值扣除
        this.hp_now = Math.max(0, this.hp_now - finalDamage);
        if (isNaN(this.hp_now)) {
            debugger;
        }
        return finalDamage + shieldAbsorbed; // 返回总伤害（包括护盾吸收的）
    }
    /**
     * 治疗
     * @param amount 治疗量
     */
    heal(amount: number) {
        if (isNaN(amount)) {
            return 0;
        }
        if (this.isDie()) {
            BattleLogger.log('info', '单位已死亡 - 无法治疗', { unitId: this.id });
            return;
        }
        this.hp_now = Math.min(this.getAttribute(Attribute_base.最大生命值), this.hp_now + amount);
        if (isNaN(this.hp_now)) {
            debugger;
        }
    }
    /**
     * 复活
     */
    reLive() {
        this.hp_now = this._rpgService.revive(this.getAttribute(Attribute_base.最大生命值));
    }
    /**
     * 添加护盾
     * @param amount 护盾量
     */
    addShield(amount: number) {
        if (isNaN(amount)) {
            return 0;
        }
        if (this.isDie()) {
            BattleLogger.log('info', '单位已死亡 - 无法添加护盾', { unitId: this.id });
            return 0;
        }
        this.shield_now += amount;
        if (isNaN(this.shield_now)) {
            debugger;
        }
        return amount;
    }

    /**
     * 获取当前护盾值
     */
    getShield(): number {
        return this.shield_now;
    }

    /**
     * 清除护盾（战斗结束时调用）
     */
    clearShield() {
        this.shield_now = 0;
    }
    /**
     * 减少技能冷却时间
     */
    reduceCooldowns() {
        this._tempSkills = this._rpgService.reduceCooldowns(this._tempSkills);
        // 转换技能数据以匹配reduceCooldowns的期望类型
        const skillsForReduce = this.selfSkill.map(skill => ({
            skillId: skill.skillId,
            reName: skill.reName,
            cooldown: skill.cooldown || 0
        }));
        const reducedSkills = this._rpgService.reduceCooldowns(skillsForReduce);

        // 更新selfSkill，保持扩展属性
        this.selfSkill = this.selfSkill.map((skill, index) => ({
            ...skill,
            cooldown: reducedSkills[index]?.cooldown || skill.cooldown || 0
        }));
        this._equipSkills = this._rpgService.reduceCooldowns(this._equipSkills);
    }

    /**
     * 检查是否死亡
     * @returns 是否死亡
     */
    isDie() {
        return this._rpgService.isDead(this.hp_now);
    }

    /**
     * 击杀处理
     */
    kill() {
        this.hp_now = 0;
    }
    getTempBoost(buffId: string, key: string): number {
        return this._tempBoosts.get(buffId)?.get(key) || 0;
    }

    /**
     * 添加临时属性提升
     * @param attributeName 属性名称
     * @param value 提升值
     * @param buffId 可选的buff ID，用于后续移除
     */
    addTempAttribute(attributeName: string, value: number, buffId?: string): void {
        const tempBuffId = buffId || 'temp_boost';
        if (!this._tempBoosts.has(tempBuffId)) {
            this._tempBoosts.set(tempBuffId, new Map());
        }
        const buffMap = this._tempBoosts.get(tempBuffId)!;
        const currentBoost = buffMap.get(attributeName) || 0;
        buffMap.set(attributeName, currentBoost + value);

        BattleLogger.log('info', '临时属性提升', {
            unitId: this.id,
            attributeName,
            boostValue: value,
            totalBoost: currentBoost + value,
            buffId: tempBuffId
        });
    }

    /**
     * 移除临时属性提升
     * @param attributeName 属性名称
     * @param buffId 可选的buff ID
     */
    removeTempAttribute(attributeName: string, buffId?: string): void {
        const tempBuffId = buffId || 'temp_boost';
        const buffMap = this._tempBoosts.get(tempBuffId);
        if (buffMap && buffMap.has(attributeName)) {
            const boostValue = buffMap.get(attributeName)!;
            buffMap.delete(attributeName);
            if (buffMap.size === 0) {
                this._tempBoosts.delete(tempBuffId);
            }

            BattleLogger.log('info', '移除临时属性提升', {
                unitId: this.id,
                attributeName,
                removedValue: boostValue,
                buffId: tempBuffId
            });
        }
    }

    /**
     * 获取技能使用数据
     * @param skillId 技能ID
     * @returns 技能使用数据
     */
    getSkillUseData(skillId: string): any {
        const skill = this._tempSkills.find(s => s.skillId === skillId);

        return skill;
    }

    /**
     * 使用技能并处理永久提升
     * @param skillId 技能ID
     * @param permanentBoostType 永久提升类型（可选）
     * @param boostAmount 提升数值（可选）
     * @returns 使用结果
     */
    useSkillWithPermanentBoost(skillId: string, permanentBoostType?: string, boostAmount?: number): {
        success: boolean;
        message: string;
    } {
        const result = this._rpgService.useSkill(this.selfSkill, skillId, permanentBoostType, boostAmount);

        if (result.success) {
            this.selfSkill = result.newSkills;
            this.reload_skills();

            BattleLogger.log('info', '技能使用成功', {
                skillId,
                useCount: result.newUseCount,
                permanentBoostType,
                boostAmount
            });
        }

        return {
            success: result.success,
            message: result.message
        };
    }

    /**
     * 升级技能
     * @param skillId 技能ID
     * @returns 升级结果
     */
    upgradeSkill(skillId: string): {
        success: boolean;
        message: string;
        leveledUp: boolean;
        newLevel: number;
    } {
        const result = this._rpgService.upgradeSkill(this.selfSkill, skillId);

        if (result.success && result.newSkills) {
            this.selfSkill = result.newSkills;
            this.reload_skills();

            if (result.leveledUp) {
                this._clientHandler.showLevelUp();
            }
        }

        return {
            success: result.success,
            message: result.message,
            leveledUp: result.leveledUp,
            newLevel: result.newLevel
        };
    }
}

